<template>
	<view class="my_motion">
		<view class="my_container">
			<view class="header">
				<video 
					:src="baseUrl + currentVideoSrc" 
					class="video" 
					id="myVideo" 
					:controls="false"
					:show-center-play-btn="false"
					@ended="endedVideo"
					@loadedmetadata="loadeddata"
				></video>
			</view>
			<view class="timer">
				<view class="time">
					<!-- 00:00:00 -->
					<text v-if="minute<10">0{{minute}}:</text>
					<text v-else>{{minute}}:</text>
					<text v-if="mill<10">0{{mill}}</text>
					<text v-else>{{mill}}</text>
					<text v-if="millisecond < 10">:0{{millisecond}}</text>
					<text v-else>:{{millisecond}}</text>
					<!-- {{currentTime}} -->
				</view>
			</view>
			<view class="sos">
				<view class="sos_no" v-if="false">
					<text>紧急救助</text>
				</view>
				<view class="sos_yeah" v-else @tap="dialClick">
					<text>紧急救助</text>
				</view>
			</view>
			<view class="operation">
				<view 
					class="pause" 
					v-if="status == 0 || status == 1 || status == 3" 
					@click="touchStart()">
						{{ status == 3 ? '继续' : '开始'}}
					</view>
				<view 
					class="pause" 
					v-else 
					@click="touchpending()">暂停</view>
				<view 
					class="stop" 
					@click="touchStop()">停止</view>
			</view>
		</view>
		
		<u-popup :show="isShow" mode="bottom" class="popup">
			<view class="popup-container">
				<view class="title">
					<view>我的运动数据</view>
					<view>{{currentDate.year}}/{{currentDate.month}}/{{currentDate.day}} {{currentDate.week}}</view>
				</view>
				<view class="current_timer">
					<view class="text">本次运动时长</view>
					<view class="complete_time">
						<!-- 00:00:00 -->
						<text v-if="minute<10">0{{minute}}:</text>
						<text v-else>{{minute}}:</text>
						<text v-if="mill<10">0{{mill}}</text>
						<text v-else>{{mill}}</text>
						<text v-if="millisecond < 10">:0{{millisecond}}</text>
						<text v-else>:{{millisecond}}</text>
					</view>
				</view>
				<view class="table">
					<view class="tab">
						<view class="tab_left">指脉氧饱和（SpO2）</view>
						<view class="tab_right">
							<!-- <text style="margin-right: 12rpx; color: #E1E1E1">记录指脉氧饱和</text> -->
							<u--input
									border="bottom"
									placeholder="记录指脉氧饱和"
									v-model="obj.spo2"
									@blur="blurErr"
							></u--input>
							<text>%</text>
						</view>
					</view>
					<view class="tab">
						<view class="tab_left">最大心率</view>
						<view class="tab_right">
							<!-- <text style="margin-right: 12rpx; color: #E1E1E1">记录心率</text> -->
							<u--input
									border="bottom"
									placeholder="记录心率"
									v-model="obj.maximumHeart"
									@blur="blurErr"
							></u--input>
							<text>次/分</text>
						</view>
					</view>
				</view>
				<view class="record">
					<u--textarea v-model="obj.other" placeholder="其他记录..."  height="100" ></u--textarea>
				</view>
				<view class="operation">
					<view class="save" @click="motionCompleteSave">保存</view>
					<view class="close" @click="closePopup">取消</view>
				</view>
				
				<!-- 提示弹窗 -->
				<u-popup
					v-if="isShowMsgPopup"
					:show="isShowMsg" 
					mode="bottom" 
					:round="50"
					@close="isShowMsg = false" 
					@open="isShowMsg=true"
					class="popup_msg"
					>
					<view class="pop_msg_container">
						<view class="pop_msg_title">您的</view>
						<view class="pop_msg_main">
							<view class="pop_msg_info">1.指脉氧饱和（SpO2）已经低于90%；</view>
							<view class="pop_msg_info">2.您的最大心率已经高（207-0.7x年龄）x（60%-70%）</view>
						</view>
						<view class="pop_msg_bottom">请您及时联系医护人员或者通过运动反馈进行咨询</view>
					</view>
				</u-popup>
			</view>
	</u-popup>
	
		
	</view>
</template>

<script>
import { addMotionLog, getContactsList, queryMotionDetail } from '@/service/api.js';
import Cache from '@/utils/cache.js';
import { year, month, day, week, zWeek } from '@/utils/date.js';
	export default {
		data() {
			return {
				baseUrl: this.$BASEImageUrl,
				isShow: false,
				isShowMsg: false,
				//是否显示弹窗
				isShowMsgPopup: false,
				
				contactsList: [],
				
				motionDetail: [],
				
				obj: {
					week: "",
					motionDuration: "",
					spo2: "",
					maximumHeart: "",
					other: ""
				},
				currentDate: {
					year: "",
					month: "",
					day: "",
					week: ""
				},
				
				// 0:未开始 1:开始 2:暂停 3:继续 4:结束 
				status: 0,
				pendingBtn: true,
				init: '',
				millisecond: 0,
				mill: 0,
				minute: 0,
				
				isPlay: false,
				videoContext: undefined,
				currentTime: "",
				currentVideoSrc: null,
				
				currentNum: 0,
				currentVideoCount: 1
			}
		},
		onLoad(options) {
			getContactsList(1, 10).then(res => {
				if(res.status == 200) this.contactsList = res.data;
			})
			
			queryMotionDetail(4).then(({data}) => {
				this.motionDetail = data.detailsList;
				
				this.currentVideoSrc = data.detailsList[0].videoUrl;
				console.log(this.motionDetail)
			})
			
			this.videoContext = uni.createVideoContext('myVideo', this)
			
			this.isShowMsgPopup = Boolean(Cache.get("userInfo").dataExceptionReminder);
		},
		onReady() {
			this.currentDate.year = year;
			this.currentDate.month = month;
			this.currentDate.day = day;
			this.currentDate.week = week;
			this.obj.week = '周' + zWeek;
		},
		methods: {
			loadeddata() {
				if(this.status != 0) {
					this.videoContext.play();		
				}
			},
			endedVideo(e) {
				console.log(this.currentNum)
				console.log(this.motionDetail.length )
				
				if(this.motionDetail.length >= this.currentVideoCount + 1) {
					this.currentNum ++;
					this.currentVideoCount ++;
					this.currentVideoSrc = this.motionDetail[this.currentNum].videoUrl;
					this.videoContext.play();		
					this.loadeddata()
					// console.log('我是第'+ num +'个视频, 成功进入循环，当前第' + currentVideoCount + '个视频，一共' + this.motionDetail.length+ '个视频')
				} else {
					console.log('运动已完成')
					this.touchpending();
					this.isShow = true;
				}
			},
			// timeUpdate(e) {
			// 	// 更新进度
			// 	const { currentTime } = e.detail
			// 	this.currentTime = currentTime
			// 	 // 播放完成
			// 	 if (Math.trunc(currentTime) === Math.trunc(duration)) {
			// 			 this.$emit('playcomplete', e)
			// 	 }
			 
			// },
			motionCompleteSave() {
				const {minute, mill, millisecond} = this;
				let currentMinute;
				let currentMill;
				let currentMillisecond;
				
				if(minute < 10) {
					currentMinute = "0" + minute;
				} else {
					currentMinute = minute;
				}
				
				if(mill < 10) {
					currentMill = "0" + mill;
				} else {
					currentMill = mill;
				}
				
				if(millisecond < 10) {
					currentMillisecond = "0" + millisecond;
				} else {
					currentMillisecond = millisecond;
				}
				
				this.obj.motionDuration = `${currentMinute}-${currentMill}-${currentMillisecond}`;
				
				//新增运动接口
				addMotionLog(this.obj).then(res => {
					if(res.status == 200) {
						uni.switchTab({
							url: '../motion/motion',
							success: () => {
								uni.showToast({
									icon: 'success',
									title: "运动完成",
									duration: 1000,
									success: () => {
										this.isShow = false;
									}
								})
							}
						})
					} else {
						uni.showToast({
							icon: "error",
							title: res.message,
							duration: 1000,
						})
					}
				})
			},
			
			dialClick() {
				const phoneList = this.contactsList.map(item => item.phone);
				const phoneNameList = this.contactsList.map(item => item.name);
				console.log(phoneList)
				uni.showActionSheet({
					itemList: phoneNameList,
					success: function (res) {
						console.log(res)
						uni.makePhoneCall({
							phoneNumber: phoneList[res.tapIndex],
						})
					},
					fail: function (res) {
						console.log(res.errMsg);
					}
				});
			},
			
			blurErr() {
				// (207 - 0.7 x60) x (60%~70%) = [（207-42）x 0.6]  ~  [（207-42）x 0.7] = 95~115

				const old = Cache.get("assessInfo") != undefined ? Cache.get("assessInfo").age : 60; //获取到的年龄值
				const age60 = parseInt(old) * .7;
				const age70 = parseInt(old) * .7;
				const beforeVal = ((207 - age60) * .6).toFixed(0);  //	60%
				const afterVal = ((207 - age70) * .7).toFixed(0); 	 //	70%
				
				console.log(beforeVal + ' - ' + afterVal)
				
				if(this.obj.spo2 < 90 && this.obj.spo2 != "") {
					this.isShowMsg = true;
					this.obj.spo2 = "";
				} 
				
				const maximumHeart = parseInt(this.obj.maximumHeart);
				// 100 > 95 || 100 < 115
				if(maximumHeart < beforeVal || maximumHeart > afterVal) {
					this.isShowMsg = true;
					this.obj.maximumHeart = "";
				} 
			},
			
			// 计时器
			timer() {
				this.millisecond += 1;
				if (this.millisecond >= 100) {
					this.millisecond = 0;
					this.mill = this.mill + 1;
				}
				if (this.mill >= 60) {
					this.mill = 0;
					this.minute = this.minute + 1;
				}					
			},
			// 点击开始按钮
			touchStart() {
				this.videoContext.play();
			
				// 开始后 把status变为2:暂停 
				this.status = 2
				this.init = setInterval(this.timer, 10)
				// 这个变量用于：在未开始前暂停继续按钮禁止点击 true是禁止
				this.pendingBtn = false
			},
			// 点击暂停按钮
			touchpending() {
				this.videoContext.pause();
				
				//点击把status变为3:继续
				this.status = 3;
				this.pendingBtn = !this.pendingBtn
				// 清除掉计时器
				clearInterval(this.init)
				 // 继续时创建新的计时器
				this.pendingBtn == false ?
				this.init = setInterval(this.timer, 10) : ''
			},
			// 点击结束按钮
			touchStop() {
				this.videoContext.pause();
				
				//先停止定时器
				clearInterval(this.init);
	
				this.isShow = true;
				this.pendingBtn = true;			
					
			},
			closePopup() {
				this.isShow = false;
				this.status = 1;
				// this.millisecond = 0;
				// this.mill = 0;
				// this.minute = 0;
			}
		}
	}
</script>

<style scoped lang="scss">
.my_motion {
	width: 100%;
	height: 100vh;
	overflow: hidden;
	position: relative;
	.my_container {
		padding: 0 40rpx;
		.header {
			height: 600rpx;
			background-color: #2BC3A4;
			border-radius: 32rpx;
			margin-bottom: 40rpx;
			overflow: hidden;
			.video {
				width: 100%;
				height: 100%;
			}
		}
		.timer {
			height: 200rpx;
			background-color: #E2FCFB;
			border-radius: 32rpx;
			font-size: 80rpx;
			color: #2BC3A4;
			text-align: center;
			line-height: 200rpx;
		}
		.sos {
			position: absolute;
			right: 40rpx;
			height: 80rpx;
			color: $uni-text-color-inverse;
			font-size: $uni-font-size-base;
			margin-top: 40rpx;
			text-align: center;
			> view {
				width: 80rpx;
				padding: 20rpx;
				border-radius: $uni-border-radius-circle;
			}
			> .sos_no {
				background-color: gray;
			}
			> .sos_yeah {
				background-color: #E15E5E;
			}
		}
		
		.operation {
			position: absolute;
			bottom: 40rpx;
			left: 20rpx;
			right: 20rpx;
			display: flex;
			justify-content: space-between;
			margin: 0 -20rpx;
			> view {
				flex: 1;
				height: 112rpx;
				line-height: 112rpx;
				text-align: center;
				color: #fff;
				background-color: #F2AF60;
				border-radius: $uni-border-radius-16;
				margin: 0 20rpx;
			}
		}
	}
	
	
	
	::v-deep .u-popup__content {
		border-top-left-radius: 52rpx;
		border-top-right-radius: 52rpx;
	}
	
	.popup-container {
		// height: 800rpx;
		// background-color: red;
		padding: 0 40rpx;
		.title {
			display: flex;
			height: 100rpx;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0 40rpx;
		}
		.current_timer {
			height: 280rpx;
			background-color: #F1F8F7;
			border-radius: $uni-border-radius-16;
			text-align: center;
			color: #2BC3A4;
			.text {
				padding: 40rpx 0 20rpx;
			}
			.complete_time {
				font-size: 80rpx;
			}
		}
		.table {
			padding: 40rpx 0 20rpx;
			.tab {
				height: 108rpx;
				// background-color: #fff;
				// font-weight: 600;
				font-size: 32rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 8rpx 20rpx;
				.tab_right {
					display: flex;
					align-items: center;
					
					justify-content: space-between;
					width: 320rpx;
					::v-deep .u-input {
						// width: 240rpx;
					}
				}
			}
		}
		.record {
			padding: 20rpx 0 40rpx;
			::v-deep .u-textarea {
				border-radius: 20rpx;
			}
		}
		.operation {
			display: flex;
			justify-content: space-between;
			margin: 20rpx -20rpx 40rpx;
			.close {
				width: 200rpx;
				color: #D3D3D3;
				border: 2rpx solid #D3D3D3;
			}
			.save {
				flex: 1;
				background-color: #F2AF60;
				color: #fff;
			}
			> view {
				height: 112rpx;
				line-height: 112rpx;
				text-align: center;
				border-radius: $uni-border-radius-16;
				margin: 0 20rpx;
			}
			
		}
	}
	
	
	
	.pop_msg_container {
		height: 600rpx;
		padding: 0 40rpx;
		font-weight: 600;
		font-size: 32rpx;
		color: #000000;
		line-height: 48rpx;
		letter-spacing: 4rpx;
		.pop_msg_title {
			padding: 60rpx 0 20rpx;
		}
		.pop_msg_main {
			overflow: hidden;
			.pop_msg_info {
				padding: 10rpx 0;
			}
		}
		.pop_msg_bottom {
			padding-top: 40rpx;
			// padding-bottom: 80rpx;
		}
	}
}
</style>
